<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<script>
var freqCounter = "";//次数
var freqInterval = "";//间隔
var freqIntervalUnit = "";//间隔单位
autoCompleteDrug("orderDrugText");
autoCompleteClinic("orderClinicText");
$(function () {
    $.ajaxSetup({ cache: false });
    if ($("#parentId").val() != null && $("#parentId").val() != "") {
        loadOrdersInfo($("#parentId").val(),'0');
    } else {
        loadOrdersConf($("#isDrug").val(), $("#repeatIncaditor").val(), $("#billingAttr").val(), '');
    }
    if($("#id").val()!=null &&$("#id").val()!=''){
        loadOrdersInfo($("#id").val(),'1');
    }
    var flag=0;
    $("#performFreq").change(function () {
        flag=flag+1;
        var performId = $(this).val();
        $.ajax({
            type: "POST",
            url: '${ctx}/sys/performFreqDict/findById?id=' + performId,
            dataType: "json",
            success: function (data) {
                if((($("#id").val()!=null&&$("#id").val()!='')||($("#parentId").val()!=null&&$("#parentId").val()!=''))&&flag==1){

                }else{
                    $("#nursePerformTime").val(data.performTime);
                }
                freqCounter = data.freqCounter;
                freqInterval = data.freqInterval;
                freqIntervalUnit = data.freqIntervalUnit;
            },
            error: function (data) {
                toastr.error('网络连接错误,请检查网络');
            }
        });
    })
    $("#btnCancel").on('click', function () {
        hideShowTableTd('contentTable', '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14', '1');
        $("#RightDiv").attr("style", "display: none");
        $("#LeftDiv").attr("class", "main-content col-lg-12");
        $("#LeftDiv").show('normal');
    })
    $("#singleDose").blur(function () {
        var s = $("#singleDose").val();
        var reg = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
        if (!reg.test(s)) {
            toastr.error("药品单次使用剂量请输入数字");
            $("#singleDose").val("");
            return false;
        }
    })
});
function loadOrdersInfo(id,flag){
    $.ajax({
        type: "POST",
        url: timestamp('${ctx}/orders/orders/findById?id=' + id),
        dataType: "json",
        success: function (data) {
            $("#isDrug").val(data.orderClass == "" || data.orderClass == null ? "2" : data.orderClass != "A" ? "1" : "0");
            $("#repeatIncaditor").val(data.repeatIncaditor);
            $("#billingAttr").val(data.billingAttr);
            loadOrdersConf($("#isDrug").val(), $("#repeatIncaditor").val(), $("#billingAttr").val(), data,flag);
        },
        error: function (data) {
            toastr.error('查询父医嘱内容错误！');
        }
    });

}
function loadOrdersConf(category, continue1, valuation, porders,flag) {
    $.ajax({
        type: 'get',
        cache: false,
        url: timestamp('${ctx}/orders/orders/findByUser?valuation=' + valuation + '&category=' + category + '&continue1=' + continue1),
        success: function (data) {
            if (data) {
                if(porders!=null && porders!=''){
//                    location.reload();
                }
                for (var i = 0; i < data.length; i++) {
                    var editFlag = data[i].edit_flag;
                    var labelId = data[i].label_id;
                    $("#" + labelId + "Div").show();
                    $("#" + labelId).attr("data-parsley-required",true);
                    if(labelId=="performFreq"&&continue1=="0"){
                        $("#performFreq option[value='E67ADE0FEA5F47679909324798FCF2FD']").attr("selected", "selected");
                        $("#performFreq").change();
                    }
                    if (editFlag == 1) {
                        $("#" + labelId).attr("disabled", 'disabled');
                    }
                }
                if (porders != '') {
                     if(flag==1){
                        var isDrug=porders.orderClass;
                        var clinicItemId=porders.clinicItemId;
                        $("#clinicItemId").val(porders.clinicItemId);
                        if(isDrug=="A"){
                            $("#orderDrugText").val(porders.orderText);
                            $("#singleDose").val(porders.singleDose);
                            $('#singleDoseUnit').attr('value',data.singleDoseUnit);
                            $("#minUnits").val(porders.minUnits);
                            $("#packageUnits").val(porders.packageUnits);
                            $("#drugSpec").val(porders.drugSpec);
                            $("#minSpec").val(porders.minSpec);
                            $("#firmName").val(porders.firmName);
                            $("#doseUnits").val(porders.doseUnits);
                        }else if(isDrug!="A"&&isDrug!=null&&isDrug!=''){
                            $("#orderClinicText").val(porders.orderText);
                            $("#performedBy").val(porders.performedBy);
                        }else if(isDrug==null || isDrug==''){
                            $("#orderEntrustText").val(porders.orderText);
                        }else{
                            toastr.error("加载医嘱内容错误");
                            return "";
                        }
                    }
                     if(continue1==1){
                        $("#nursePerformTime").val(porders.nursePerformTime);
                     }
                    $("#performFreq option[value="+porders.performFreq +"]").attr("selected", "selected");
                    $("#performFreq").change();
                    if(category==0){
                        $("#administration option[value=" + porders.administration + "]").attr("selected", "selected");
                        $("#administration").change();
                    }
                    if(flag==0){
                        $("#performFreq").attr('disabled','disabled');
                        $("#administration").attr("disabled",'disabled');
                    }
                 }
            } else {
                toastr.error("参数选择错误");
            }
        }
    });
}
//检查执行时间
function checkValue() {
    var nursePerformTime = $("#nursePerformTime").val();
    nursePerformTime = nursePerformTime.replace(/[^\w&-]|_/ig, '');
    var reg = /^[1-9]+[0-9]*]*$/;
    var narr = nursePerformTime.split("-");
    for (var i = 0; i < narr.length; i++) {
        if (!reg.test(narr[i])) {
            toastr.error("执行时间请输入数字！");
            $("#nursePerformTime").val("")
            return false;
        }
    }
    //1 判断间隔单位
    if (freqIntervalUnit.indexOf('日') != -1) {
        var arr = nursePerformTime.split("-");
        if (arr.length != freqCounter) {
            toastr.error("执行时间与所选执行频次不符！");
            $("#nursePerformTime").val("")
            return false;
        }
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == arr[i + 1]) {
                toastr.error("执行时间点数不能重复！");
                $("#nursePerformTime").val("")
                return false;
            }
            if (arr[i] > 24) {
                toastr.error("执行时间点数不能大于24！");
                $("#nursePerformTime").val("")
                return false;
            }
        }
    } else if (freqIntervalUnit.indexOf('周') != -1) {
        var arr = nursePerformTime.split("-");
        if (arr.length != freqCounter) {
            toastr.error("执行时间与所选执行频次不符！");
            $("#nursePerformTime").val("")
            return false;
        }
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == arr[i + 1]) {
                toastr.error("执行时间星期不能重复！");
                $("#nursePerformTime").val("")
                return false;
            }
            if (arr[i] > 7) {
                toastr.error("星期不能大于7！");
                $("#nursePerformTime").val("");
                return false;
            }
        }
    } else if (freqIntervalUnit.indexOf('小时') != -1) {
        var count = 24 / freqInterval;
        var arr = nursePerformTime.split("-");
        if (arr.length != count) {
            toastr.error("执行时间与所选执行频次不符！");
            $("#nursePerformTime").val("")
            return false;
        }
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == arr[i + 1]) {
                toastr.error("执行时间点数不能重复！");
                $("#nursePerformTime").val("")
                return false;
            }
            if (arr[i] > 24) {
                toastr.error("执行时间点数不能大于24！");
                $("#nursePerformTime").val("")
                return false;
            }
        }

    } else {
        toastr.error("执行时间非法！");
        return false;
    }

}
/*诊疗项目补全*/
function autoCompleteClinic(inputId) {
    $("#" + inputId).flushCache();
    var url = timestamp("${ctx}/oper/clinicItemDict/automatic?removeClass=A,B");
    autoComplete(inputId, url,
            function (data) {
                var rows = [];
                for (var i = 0; i < data.length; i++) {
                    rows[rows.length] = {
                        data: data[i],
                        value: data[i].id,
                        result: data[i].itemName
                    };
                }
                return rows;
            }, function (data, i, max) {
                return "类别：" + data.expand1 + "|名称：" + data.itemName + "|价格：" + data.price + "元";
            }, function (event, data, formatted) {
                $("#clinicItemId").val(data.id);
                $("#orderClass").val(data.itemClass);
                $("#price").val(data.price);
            })
}
/*药品自动补全*/
function autoCompleteDrug(inputId) {
    $("#" + inputId).flushCache();            //刷新缓存（非常重要）
    var url = timestamp("${ctx}/orders/orders/autoComplete");
    autoComplete(inputId, url,
            function (data) {
                var rows = [];
                for (var i = 0; i < data.length; i++) {
                    rows[rows.length] = {
                        data: data[i],
                        value: data[i].price_id,
                        result: data[i].drug_name
                    };
                }
                return rows;
            }, function (data, i, max) {
                return data.drug_name + "|" + data.package_spec + "|" + data.packageunit + "|" + data.min_spec + "|" + data.minunits + "|" + data.firm_name + "|库存量：" + data.quantity+"|药房：" + data.storage_name;
            }, function (event, data, formatted) {
                if(data.quantity==0){
                        $("#orderDrugText").val("");
                        toastr.error("此药品的库存量为0,请更换其他药品！");
                        return false;
                }else{
                    $("#clinicItemId").val(data.price_id);
                    $("#orderClass").val(data.durg_class);
                    $('#singleDoseUnit').val(data.dose_per_unit);
                    $('#minUnits').val(data.minunits);
                    $('#packageUnits').val(data.packageunit);
                    $('#minSpec').val(data.min_spec);
                    $('#drugSpec').val(data.package_spec);
                    $('#firmId').val(data.firm_id);
                    $('#firmName').val(data.firm_name);
                    $('#stockNum').val(data.quantity);
                    $('#price').val(data.price);
                    $('#doseUnits').val(data.dose_units);
                }
             })
 }

</script>
<div class="content-wrap">
    <div class="wrapper" style="bottom: 50px;">
        <section class="panel panel-default">
            <div class="panel-body">
                <div class="col-lg-12" id="outDiv">
                    <form:form id="inputForm" data-parsley-validate="" modelAttribute="orders" method="post"
                               class="form-horizontal"
                               onsubmit="return formSaveLoad('rigthDoctorCenterDiv','inputForm','${ctx}/orders/orders/save','${ctx}/orders/orders/index?patientId='+$('#patientId').val()+'&visitId='+$('#visitId').val());">
                        <form:hidden path="isDrug" value="${ordersConf.category}"/>
                        <form:hidden path="repeatIncaditor" value="${ordersConf.continue1}"/>
                        <form:hidden path="billingAttr" value="${ordersConf.valuation}"/>
                        <form:hidden path="patientId"/>
                        <form:hidden path="visitId"/>
                        <form:hidden path="firmId"/>
                        <form:hidden path="parent.id" id="parentId"/>
                        <form:hidden path="clinicItemId"/>
                        <form:hidden path="id"/>
                        <form:hidden path="orderClass"/>
                        <form:hidden path="orderStatus" value="0"/>
                        <form:hidden path="isApply" value="0"/>
                        <div class="form-group" style="display:none;" id="orderDrugTextDiv">
                            <div class="col-sm-12">
                                <form:input path="orderDrugText" id="orderDrugText" htmlEscape="false"
                                            class="form-control" maxlength="32"
                                            placeholder="请搜索药品"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="orderClinicTextDiv">
                            <div class="col-sm-12">
                                <form:input path="orderClinicText" id="orderClinicText" htmlEscape="false"
                                            class="form-control" maxlength="32"
                                            placeholder="请搜索诊疗项目"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="orderEntrustTextDiv">
                            <div class="col-sm-12">
                                <form:input path="orderEntrustText" id="orderEntrustText" htmlEscape="false"
                                            class="form-control" maxlength="32"
                                            placeholder="请输入嘱托内容或自带药名称"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="singleDoseDiv">
                            <div class="col-sm-12">
                                药品单次使用量:
                                <form:input path="singleDose" id="singleDose" htmlEscape="false" class="form-control"
                                            maxlength="20" placeholder="请输入药品单次使用量" />
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="singleDoseUnitDiv">
                            <div class="col-sm-12">
                                最小单位剂量:
                                <form:input path="singleDoseUnit" id="singleDoseUnit" htmlEscape="false" class="form-control"
                                            maxlength="20" placeholder="最小单位剂量"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="doseUnitsDiv">
                            <div class="col-sm-12">
                                剂量单位:
                                <form:input path="doseUnits" id="doseUnits" htmlEscape="false" class="form-control"
                                            maxlength="20" placeholder="剂量单位"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="minUnitsDiv">
                            <div class="col-sm-12">
                                <form:input path="minUnits" id="minUnits" htmlEscape="false" class="form-control"
                                            maxlength="20" placeholder="药品最小单位"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="packageUnitsDiv">
                            <div class="col-sm-12">
                                <form:input path="packageUnits" id="packageUnits" htmlEscape="false" class="form-control"
                                            maxlength="20" placeholder="药品包装单位"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="minSpecDiv">
                            <div class="col-sm-12">
                                <form:input path="minSpec" id="minSpec" htmlEscape="false" class="form-control"
                                            maxlength="20" placeholder="药品最小规格"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="drugSpecDiv">
                            <div class="col-sm-12">
                                <form:input path="drugSpec" id="drugSpec" htmlEscape="false" class="form-control"
                                            maxlength="20" placeholder="药品包装规格"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="firmNameDiv">
                            <div class="col-sm-12">
                                <form:input path="firmName" id="firmName" htmlEscape="false" class="form-control"
                                            maxlength="20" placeholder="药品生产厂商"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="stockNumDiv">
                            <div class="col-sm-12">
                                库存量:<form:input path="stockNum" id="stockNum" htmlEscape="false" class="form-control"
                                                maxlength="20" placeholder="库存量"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="priceDiv">
                            <div class="col-sm-12">
                                单价:<form:input path="price" id="price" htmlEscape="false" class="form-control"
                                               maxlength="20" placeholder="单价"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="administrationDiv">
                            <div class="col-sm-12">
                                <form:select path="administration" id="administration" class="form-control">
                                    <form:option value="" label="请选择用药途径"/>
                                    <form:options items="${fns:getSysDictList('ADMINISTRATION_DICT')}" itemLabel="label"
                                                  itemValue="id" htmlEscape="false"/>
                                </form:select>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="performFreqDiv">
                            <div class="col-sm-12">
                                <form:select path="performFreq" id="performFreq" class="form-control"
                                             itemLabel="freqDesc" itemValue="id">
                                    <form:option value="" label="请选择医嘱执行频次"/>
                                    <form:options items="${fns:findFreqList()}" itemLabel="freqDesc" itemValue="id"
                                                  htmlEscape="false"/>
                                </form:select>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="nursePerformTimeDiv">
                            <div class="col-sm-12">
                                <form:input path="nursePerformTime"
                                            onkeypress="if(event.keyCode!=45 && (event.keyCode<48 || event.keyCode>57)) event.returnValue=false"
                                            onblur="checkValue()" style="ime-mode:disabled" id="nursePerformTime"
                                            htmlEscape="false" class="form-control"
                                            maxlength="100" placeholder="请根据选择的频次输入合法的护士执行时间"/>
                            </div>
                        </div>
                        <div class="form-group" style="display:none;" id="performedByDiv">
                            <div class="col-sm-12">
                                    <form:select path="performedBy" id="performedBy" class="form-control"
                                                 itemLabel="deptName" itemValue="id">
                                        <form:option value="" label="请选择执行科室"/>
                                        <form:options items="${fns:findWardCode('0,1,2')}" itemLabel="deptName" itemValue="id"
                                                      htmlEscape="false"/>
                                    </form:select>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-12">
                                <form:textarea path="doctInstruction" htmlEscape="false" class="form-control"
                                               maxlength="200" placeholder="请输入对于新开医嘱的说明"/>
                            </div>
                        </div>
                        <div class="form-group" >
                            <div class="col-sm-offset-2 col-sm-10">
                                <input  class="btn btn-primary" type="submit" value="保存">&nbsp;
                                <input id="btnCancel" class="btn" type="button" value="关 闭"></div>
                        </div>
                    </form:form>
                </div>
            </div>
        </section>
    </div>
</div>

